package org.primefaces.model.chart.flow;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.chart.ChartModel;

/**
 * 流程图形对象
 * 
 * @author 潘巍（Peter Pan）
 * @since 2011-2-11 上午11:08:31
 */
public class FlowChartModel extends ChartModel implements Serializable {

	private static final long serialVersionUID = 3323112534322194189L;

	private final static Logger logger = Logger.getLogger(FlowChartModel.class
			.getName());

	public static final String CANVAS_ELS = "canvasEls";

	public static final String DEFAULT_ATTRIBUTES = "defaultAttributes";

	/**
	 * 页面元素集合
	 */
	private FlowElementSet elementSet;

	private FlowDefaultAttributes defaultAttributes;

	public FlowElementSet getElementSet() {
		return elementSet;
	}

	public void setElementSet(FlowElementSet elementSet) {
		this.elementSet = elementSet;
	}

	public FlowDefaultAttributes getDefaultAttributes() {
		return defaultAttributes;
	}

	public void setDefaultAttributes(FlowDefaultAttributes defaultAttributes) {
		this.defaultAttributes = defaultAttributes;
	}

	public JSONObject toJSON() {
		try {
			JSONObject jo = new JSONObject();
			if (this.elementSet != null)
				jo.put(CANVAS_ELS, this.elementSet.toJSON());
			if (this.defaultAttributes != null)
				jo.put(DEFAULT_ATTRIBUTES, this.defaultAttributes.toJSON());
			return jo;
		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer to json object.");
		}
		return null;
	}

	public void construct(JSONObject json) {
		try {
			if (json.has(CANVAS_ELS)) {
				if (this.elementSet == null)
					this.elementSet = new FlowElementSet();
				this.elementSet.construct(json.getJSONObject(CANVAS_ELS));
			}

			if (json.has(DEFAULT_ATTRIBUTES)) {
				if (this.defaultAttributes == null)
					this.defaultAttributes = new FlowDefaultAttributes();
				this.defaultAttributes.construct(json
						.getJSONObject(DEFAULT_ATTRIBUTES));
			}
		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer from json object.");
		}
	}

	public void clear() {
		if (this.elementSet != null)
			this.elementSet.clear();
		if (this.defaultAttributes != null)
			this.defaultAttributes.clear();
	}

}
